package com.lry.sso.auth.common.bean;

import com.lry.sso.auth.common.util.SessionInfo;
import org.springframework.core.NamedThreadLocal;

import java.util.List;

/**
 * 请求上下文
 * 使用时记得remove
 *
 * @author newland
 */
public class RequestInfoContext {

    /**
     * 当前请求的token信息
     */
    private static NamedThreadLocal<String> tokenThreadLocal = new NamedThreadLocal<>("token");

    /**
     * 当前请求的token转换后的用户信息
     */
    private static NamedThreadLocal<SessionInfo> sessionInfoThreadLocal = new NamedThreadLocal<>("SessionInfo");

    private static NamedThreadLocal<UrlSession> urlSessionThreadLocal = new NamedThreadLocal<>("urlSession");

    public static String getToken() {
        checkSessionInfo();
        return tokenThreadLocal.get();
    }

    public static void setToken(String token) {
        tokenThreadLocal.set(token);
    }

    public static SessionInfo getSession() {
        checkSessionInfo();
        return sessionInfoThreadLocal.get();
    }

    public static Long getUserId() {
        checkSessionInfo();
        return getSession().getUserId();
    }

    public static void set(SessionInfo sessionInfo) {
        sessionInfoThreadLocal.set(sessionInfo);
    }

    public static void checkSessionInfo() {
        //本地免登入
        SessionInfo sessionInfo = sessionInfoThreadLocal.get();
        if (sessionInfo == null) {
//            throw new SystemException(ErrorBuilder.build(SystemErrorCode.ERR_CODE_SESSION_NULL, SystemErrorCode.ERR_MSG_SESSION_NULL));
        }
    }

    public static String getUserName(){
        checkSessionInfo();
        return getSession().getUserName();
    }

    //获取当前用户的roleIds
    public static List<Integer> getUserRoleIds(){
        checkSessionInfo();
        return getSession().getRoleIdList();
    }

    public static UrlSession getUrlSession() {
        return urlSessionThreadLocal.get();
    }

    public static void setUrlSession(UrlSession urlSession) {
        urlSessionThreadLocal.set(urlSession);
    }

    /**
     * 移除内存占用
     */
    public static void remove(){
        tokenThreadLocal.remove();
        urlSessionThreadLocal.remove();
        sessionInfoThreadLocal.remove();
    }
}